package org.openwork.portlet.skillmanagement.service.persistence;

import com.liferay.portal.NoSuchModelException;
import com.liferay.portal.kernel.annotation.BeanReference;
import com.liferay.portal.kernel.cache.CacheRegistry;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.InstanceFactory;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.BatchSessionUtil;
import com.liferay.portal.service.persistence.ResourcePersistence;
import com.liferay.portal.service.persistence.UserPersistence;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;

import org.openwork.portlet.skillmanagement.NoSuchUserException;
import org.openwork.portlet.skillmanagement.model.SkillUser;
import org.openwork.portlet.skillmanagement.model.impl.SkillUserImpl;
import org.openwork.portlet.skillmanagement.model.impl.SkillUserModelImpl;
import org.openwork.portlet.skillmanagement.service.persistence.SkillCategoryPersistence;
import org.openwork.portlet.skillmanagement.service.persistence.SkillPersistence;
import org.openwork.portlet.skillmanagement.service.persistence.SkillUserPersistence;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * <a href="SkillUserPersistenceImpl.java.html"><b><i>View Source</i></b></a>
 *
 * <p>
 * ServiceBuilder generated this class. Modifications in this class will be
 * overwritten the next time is generated.
 * </p>
 *
 * @author    Samuel Garcia Martinez
 * @see       SkillUserPersistence
 * @see       SkillUserUtil
 * @generated
 */
public class SkillUserPersistenceImpl extends BasePersistenceImpl<SkillUser>
    implements SkillUserPersistence {
    public static final String FINDER_CLASS_NAME_ENTITY = SkillUserImpl.class.getName();
    public static final String FINDER_CLASS_NAME_LIST = FINDER_CLASS_NAME_ENTITY +
        ".List";
    public static final FinderPath FINDER_PATH_FIND_BY_USERID = new FinderPath(SkillUserModelImpl.ENTITY_CACHE_ENABLED,
            SkillUserModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
            "findByUserId",
            new String[] {
                Long.class.getName(),
                
            "java.lang.Integer", "java.lang.Integer",
                "com.liferay.portal.kernel.util.OrderByComparator"
            });
    public static final FinderPath FINDER_PATH_COUNT_BY_USERID = new FinderPath(SkillUserModelImpl.ENTITY_CACHE_ENABLED,
            SkillUserModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
            "countByUserId", new String[] { Long.class.getName() });
    public static final FinderPath FINDER_PATH_FIND_BY_SKILLID = new FinderPath(SkillUserModelImpl.ENTITY_CACHE_ENABLED,
            SkillUserModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
            "findBySkillId",
            new String[] {
                Long.class.getName(),
                
            "java.lang.Integer", "java.lang.Integer",
                "com.liferay.portal.kernel.util.OrderByComparator"
            });
    public static final FinderPath FINDER_PATH_COUNT_BY_SKILLID = new FinderPath(SkillUserModelImpl.ENTITY_CACHE_ENABLED,
            SkillUserModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
            "countBySkillId", new String[] { Long.class.getName() });
    public static final FinderPath FINDER_PATH_FIND_ALL = new FinderPath(SkillUserModelImpl.ENTITY_CACHE_ENABLED,
            SkillUserModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
            "findAll", new String[0]);
    public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(SkillUserModelImpl.ENTITY_CACHE_ENABLED,
            SkillUserModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
            "countAll", new String[0]);
    private static final String _SQL_SELECT_SKILLUSER = "SELECT skillUser FROM SkillUser skillUser";
    private static final String _SQL_SELECT_SKILLUSER_WHERE = "SELECT skillUser FROM SkillUser skillUser WHERE ";
    private static final String _SQL_COUNT_SKILLUSER = "SELECT COUNT(*) FROM SkillUser skillUser";
    private static final String _SQL_COUNT_SKILLUSER_WHERE = "SELECT COUNT(*) FROM SkillUser skillUser WHERE ";
    private static final String _FINDER_COLUMN_USERID_USERID_2 = "skillUser.id.userId = ?";
    private static final String _FINDER_COLUMN_SKILLID_SKILLID_2 = "skillUser.id.skillId = ?";
    private static final String _ORDER_BY_ENTITY_ALIAS = "skillUser.";
    private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No SkillUser exists with the primary key ";
    private static final String _NO_SUCH_ENTITY_WITH_KEY = "No SkillUser exists with the key {";
    private static Log _log = LogFactoryUtil.getLog(SkillUserPersistenceImpl.class);
    @BeanReference(type = SkillCategoryPersistence.class)
    protected SkillCategoryPersistence skillCategoryPersistence;
    @BeanReference(type = SkillPersistence.class)
    protected SkillPersistence skillPersistence;
    @BeanReference(type = SkillUserPersistence.class)
    protected SkillUserPersistence skillUserPersistence;
    @BeanReference(type = ResourcePersistence.class)
    protected ResourcePersistence resourcePersistence;
    @BeanReference(type = UserPersistence.class)
    protected UserPersistence userPersistence;

    public void cacheResult(SkillUser skillUser) {
        EntityCacheUtil.putResult(SkillUserModelImpl.ENTITY_CACHE_ENABLED,
            SkillUserImpl.class, skillUser.getPrimaryKey(), skillUser);
    }

    public void cacheResult(List<SkillUser> skillUsers) {
        for (SkillUser skillUser : skillUsers) {
            if (EntityCacheUtil.getResult(
                        SkillUserModelImpl.ENTITY_CACHE_ENABLED,
                        SkillUserImpl.class, skillUser.getPrimaryKey(), this) == null) {
                cacheResult(skillUser);
            }
        }
    }

    public void clearCache() {
        CacheRegistry.clear(SkillUserImpl.class.getName());
        EntityCacheUtil.clearCache(SkillUserImpl.class.getName());
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
    }

    public void clearCache(SkillUser skillUser) {
        EntityCacheUtil.removeResult(SkillUserModelImpl.ENTITY_CACHE_ENABLED,
            SkillUserImpl.class, skillUser.getPrimaryKey());
    }

    public SkillUser create(SkillUserPK skillUserPK) {
        SkillUser skillUser = new SkillUserImpl();

        skillUser.setNew(true);
        skillUser.setPrimaryKey(skillUserPK);

        return skillUser;
    }

    public SkillUser remove(Serializable primaryKey)
        throws NoSuchModelException, SystemException {
        return remove((SkillUserPK) primaryKey);
    }

    public SkillUser remove(SkillUserPK skillUserPK)
        throws NoSuchUserException, SystemException {
        Session session = null;

        try {
            session = openSession();

            SkillUser skillUser = (SkillUser) session.get(SkillUserImpl.class,
                    skillUserPK);

            if (skillUser == null) {
                if (_log.isWarnEnabled()) {
                    _log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + skillUserPK);
                }

                throw new NoSuchUserException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
                    skillUserPK);
            }

            return remove(skillUser);
        } catch (NoSuchUserException nsee) {
            throw nsee;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    public SkillUser remove(SkillUser skillUser) throws SystemException {
        for (ModelListener<SkillUser> listener : listeners) {
            listener.onBeforeRemove(skillUser);
        }

        skillUser = removeImpl(skillUser);

        for (ModelListener<SkillUser> listener : listeners) {
            listener.onAfterRemove(skillUser);
        }

        return skillUser;
    }

    protected SkillUser removeImpl(SkillUser skillUser)
        throws SystemException {
        skillUser = toUnwrappedModel(skillUser);

        Session session = null;

        try {
            session = openSession();

            if (skillUser.isCachedModel() || BatchSessionUtil.isEnabled()) {
                Object staleObject = session.get(SkillUserImpl.class,
                        skillUser.getPrimaryKeyObj());

                if (staleObject != null) {
                    session.evict(staleObject);
                }
            }

            session.delete(skillUser);

            session.flush();
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }

        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

        EntityCacheUtil.removeResult(SkillUserModelImpl.ENTITY_CACHE_ENABLED,
            SkillUserImpl.class, skillUser.getPrimaryKey());

        return skillUser;
    }

    public SkillUser updateImpl(
        org.openwork.portlet.skillmanagement.model.SkillUser skillUser,
        boolean merge) throws SystemException {
        skillUser = toUnwrappedModel(skillUser);

        Session session = null;

        try {
            session = openSession();

            BatchSessionUtil.update(session, skillUser, merge);

            skillUser.setNew(false);
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }

        FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

        EntityCacheUtil.putResult(SkillUserModelImpl.ENTITY_CACHE_ENABLED,
            SkillUserImpl.class, skillUser.getPrimaryKey(), skillUser);

        return skillUser;
    }

    protected SkillUser toUnwrappedModel(SkillUser skillUser) {
        if (skillUser instanceof SkillUserImpl) {
            return skillUser;
        }

        SkillUserImpl skillUserImpl = new SkillUserImpl();

        skillUserImpl.setNew(skillUser.isNew());
        skillUserImpl.setPrimaryKey(skillUser.getPrimaryKey());

        skillUserImpl.setUserId(skillUser.getUserId());
        skillUserImpl.setSkillId(skillUser.getSkillId());
        skillUserImpl.setAuditUserId(skillUser.getAuditUserId());
        skillUserImpl.setCreateDate(skillUser.getCreateDate());
        skillUserImpl.setModifiedDate(skillUser.getModifiedDate());
        skillUserImpl.setExperience(skillUser.getExperience());

        return skillUserImpl;
    }

    public SkillUser findByPrimaryKey(Serializable primaryKey)
        throws NoSuchModelException, SystemException {
        return findByPrimaryKey((SkillUserPK) primaryKey);
    }

    public SkillUser findByPrimaryKey(SkillUserPK skillUserPK)
        throws NoSuchUserException, SystemException {
        SkillUser skillUser = fetchByPrimaryKey(skillUserPK);

        if (skillUser == null) {
            if (_log.isWarnEnabled()) {
                _log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + skillUserPK);
            }

            throw new NoSuchUserException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
                skillUserPK);
        }

        return skillUser;
    }

    public SkillUser fetchByPrimaryKey(Serializable primaryKey)
        throws SystemException {
        return fetchByPrimaryKey((SkillUserPK) primaryKey);
    }

    public SkillUser fetchByPrimaryKey(SkillUserPK skillUserPK)
        throws SystemException {
        SkillUser skillUser = (SkillUser) EntityCacheUtil.getResult(SkillUserModelImpl.ENTITY_CACHE_ENABLED,
                SkillUserImpl.class, skillUserPK, this);

        if (skillUser == null) {
            Session session = null;

            try {
                session = openSession();

                skillUser = (SkillUser) session.get(SkillUserImpl.class,
                        skillUserPK);
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (skillUser != null) {
                    cacheResult(skillUser);
                }

                closeSession(session);
            }
        }

        return skillUser;
    }

    public List<SkillUser> findByUserId(long userId) throws SystemException {
        return findByUserId(userId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
    }

    public List<SkillUser> findByUserId(long userId, int start, int end)
        throws SystemException {
        return findByUserId(userId, start, end, null);
    }

    public List<SkillUser> findByUserId(long userId, int start, int end,
        OrderByComparator orderByComparator) throws SystemException {
        Object[] finderArgs = new Object[] {
                new Long(userId),
                
                String.valueOf(start), String.valueOf(end),
                String.valueOf(orderByComparator)
            };

        List<SkillUser> list = (List<SkillUser>) FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_USERID,
                finderArgs, this);

        if (list == null) {
            Session session = null;

            try {
                session = openSession();

                StringBundler query = null;

                if (orderByComparator != null) {
                    query = new StringBundler(3 +
                            (orderByComparator.getOrderByFields().length * 3));
                } else {
                    query = new StringBundler(2);
                }

                query.append(_SQL_SELECT_SKILLUSER_WHERE);

                query.append(_FINDER_COLUMN_USERID_USERID_2);

                if (orderByComparator != null) {
                    appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
                        orderByComparator);
                }

                String sql = query.toString();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(userId);

                list = (List<SkillUser>) QueryUtil.list(q, getDialect(), start,
                        end);
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (list == null) {
                    list = new ArrayList<SkillUser>();
                }

                cacheResult(list);

                FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_USERID,
                    finderArgs, list);

                closeSession(session);
            }
        }

        return list;
    }

    public SkillUser findByUserId_First(long userId,
        OrderByComparator orderByComparator)
        throws NoSuchUserException, SystemException {
        List<SkillUser> list = findByUserId(userId, 0, 1, orderByComparator);

        if (list.isEmpty()) {
            StringBundler msg = new StringBundler(4);

            msg.append(_NO_SUCH_ENTITY_WITH_KEY);

            msg.append("userId=");
            msg.append(userId);

            msg.append(StringPool.CLOSE_CURLY_BRACE);

            throw new NoSuchUserException(msg.toString());
        } else {
            return list.get(0);
        }
    }

    public SkillUser findByUserId_Last(long userId,
        OrderByComparator orderByComparator)
        throws NoSuchUserException, SystemException {
        int count = countByUserId(userId);

        List<SkillUser> list = findByUserId(userId, count - 1, count,
                orderByComparator);

        if (list.isEmpty()) {
            StringBundler msg = new StringBundler(4);

            msg.append(_NO_SUCH_ENTITY_WITH_KEY);

            msg.append("userId=");
            msg.append(userId);

            msg.append(StringPool.CLOSE_CURLY_BRACE);

            throw new NoSuchUserException(msg.toString());
        } else {
            return list.get(0);
        }
    }

    public SkillUser[] findByUserId_PrevAndNext(SkillUserPK skillUserPK,
        long userId, OrderByComparator orderByComparator)
        throws NoSuchUserException, SystemException {
        SkillUser skillUser = findByPrimaryKey(skillUserPK);

        Session session = null;

        try {
            session = openSession();

            SkillUser[] array = new SkillUserImpl[3];

            array[0] = getByUserId_PrevAndNext(session, skillUser, userId,
                    orderByComparator, true);

            array[1] = skillUser;

            array[2] = getByUserId_PrevAndNext(session, skillUser, userId,
                    orderByComparator, false);

            return array;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    protected SkillUser getByUserId_PrevAndNext(Session session,
        SkillUser skillUser, long userId, OrderByComparator orderByComparator,
        boolean previous) {
        StringBundler query = null;

        if (orderByComparator != null) {
            query = new StringBundler(6 +
                    (orderByComparator.getOrderByFields().length * 6));
        } else {
            query = new StringBundler(3);
        }

        query.append(_SQL_SELECT_SKILLUSER_WHERE);

        query.append(_FINDER_COLUMN_USERID_USERID_2);

        if (orderByComparator != null) {
            String[] orderByFields = orderByComparator.getOrderByFields();

            if (orderByFields.length > 0) {
                query.append(WHERE_AND);
            }

            for (int i = 0; i < orderByFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByFields[i]);

                if ((i + 1) < orderByFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN_HAS_NEXT);
                    } else {
                        query.append(WHERE_LESSER_THAN_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN);
                    } else {
                        query.append(WHERE_LESSER_THAN);
                    }
                }
            }

            query.append(ORDER_BY_CLAUSE);

            for (int i = 0; i < orderByFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByFields[i]);

                if ((i + 1) < orderByFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC_HAS_NEXT);
                    } else {
                        query.append(ORDER_BY_DESC_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC);
                    } else {
                        query.append(ORDER_BY_DESC);
                    }
                }
            }
        }

        String sql = query.toString();

        Query q = session.createQuery(sql);

        q.setFirstResult(0);
        q.setMaxResults(2);

        QueryPos qPos = QueryPos.getInstance(q);

        qPos.add(userId);

        if (orderByComparator != null) {
            Object[] values = orderByComparator.getOrderByValues(skillUser);

            for (Object value : values) {
                qPos.add(value);
            }
        }

        List<SkillUser> list = q.list();

        if (list.size() == 2) {
            return list.get(1);
        } else {
            return null;
        }
    }

    public List<SkillUser> findBySkillId(long skillId)
        throws SystemException {
        return findBySkillId(skillId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
    }

    public List<SkillUser> findBySkillId(long skillId, int start, int end)
        throws SystemException {
        return findBySkillId(skillId, start, end, null);
    }

    public List<SkillUser> findBySkillId(long skillId, int start, int end,
        OrderByComparator orderByComparator) throws SystemException {
        Object[] finderArgs = new Object[] {
                new Long(skillId),
                
                String.valueOf(start), String.valueOf(end),
                String.valueOf(orderByComparator)
            };

        List<SkillUser> list = (List<SkillUser>) FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_SKILLID,
                finderArgs, this);

        if (list == null) {
            Session session = null;

            try {
                session = openSession();

                StringBundler query = null;

                if (orderByComparator != null) {
                    query = new StringBundler(3 +
                            (orderByComparator.getOrderByFields().length * 3));
                } else {
                    query = new StringBundler(2);
                }

                query.append(_SQL_SELECT_SKILLUSER_WHERE);

                query.append(_FINDER_COLUMN_SKILLID_SKILLID_2);

                if (orderByComparator != null) {
                    appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
                        orderByComparator);
                }

                String sql = query.toString();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(skillId);

                list = (List<SkillUser>) QueryUtil.list(q, getDialect(), start,
                        end);
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (list == null) {
                    list = new ArrayList<SkillUser>();
                }

                cacheResult(list);

                FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_SKILLID,
                    finderArgs, list);

                closeSession(session);
            }
        }

        return list;
    }

    public SkillUser findBySkillId_First(long skillId,
        OrderByComparator orderByComparator)
        throws NoSuchUserException, SystemException {
        List<SkillUser> list = findBySkillId(skillId, 0, 1, orderByComparator);

        if (list.isEmpty()) {
            StringBundler msg = new StringBundler(4);

            msg.append(_NO_SUCH_ENTITY_WITH_KEY);

            msg.append("skillId=");
            msg.append(skillId);

            msg.append(StringPool.CLOSE_CURLY_BRACE);

            throw new NoSuchUserException(msg.toString());
        } else {
            return list.get(0);
        }
    }

    public SkillUser findBySkillId_Last(long skillId,
        OrderByComparator orderByComparator)
        throws NoSuchUserException, SystemException {
        int count = countBySkillId(skillId);

        List<SkillUser> list = findBySkillId(skillId, count - 1, count,
                orderByComparator);

        if (list.isEmpty()) {
            StringBundler msg = new StringBundler(4);

            msg.append(_NO_SUCH_ENTITY_WITH_KEY);

            msg.append("skillId=");
            msg.append(skillId);

            msg.append(StringPool.CLOSE_CURLY_BRACE);

            throw new NoSuchUserException(msg.toString());
        } else {
            return list.get(0);
        }
    }

    public SkillUser[] findBySkillId_PrevAndNext(SkillUserPK skillUserPK,
        long skillId, OrderByComparator orderByComparator)
        throws NoSuchUserException, SystemException {
        SkillUser skillUser = findByPrimaryKey(skillUserPK);

        Session session = null;

        try {
            session = openSession();

            SkillUser[] array = new SkillUserImpl[3];

            array[0] = getBySkillId_PrevAndNext(session, skillUser, skillId,
                    orderByComparator, true);

            array[1] = skillUser;

            array[2] = getBySkillId_PrevAndNext(session, skillUser, skillId,
                    orderByComparator, false);

            return array;
        } catch (Exception e) {
            throw processException(e);
        } finally {
            closeSession(session);
        }
    }

    protected SkillUser getBySkillId_PrevAndNext(Session session,
        SkillUser skillUser, long skillId, OrderByComparator orderByComparator,
        boolean previous) {
        StringBundler query = null;

        if (orderByComparator != null) {
            query = new StringBundler(6 +
                    (orderByComparator.getOrderByFields().length * 6));
        } else {
            query = new StringBundler(3);
        }

        query.append(_SQL_SELECT_SKILLUSER_WHERE);

        query.append(_FINDER_COLUMN_SKILLID_SKILLID_2);

        if (orderByComparator != null) {
            String[] orderByFields = orderByComparator.getOrderByFields();

            if (orderByFields.length > 0) {
                query.append(WHERE_AND);
            }

            for (int i = 0; i < orderByFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByFields[i]);

                if ((i + 1) < orderByFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN_HAS_NEXT);
                    } else {
                        query.append(WHERE_LESSER_THAN_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(WHERE_GREATER_THAN);
                    } else {
                        query.append(WHERE_LESSER_THAN);
                    }
                }
            }

            query.append(ORDER_BY_CLAUSE);

            for (int i = 0; i < orderByFields.length; i++) {
                query.append(_ORDER_BY_ENTITY_ALIAS);
                query.append(orderByFields[i]);

                if ((i + 1) < orderByFields.length) {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC_HAS_NEXT);
                    } else {
                        query.append(ORDER_BY_DESC_HAS_NEXT);
                    }
                } else {
                    if (orderByComparator.isAscending() ^ previous) {
                        query.append(ORDER_BY_ASC);
                    } else {
                        query.append(ORDER_BY_DESC);
                    }
                }
            }
        }

        String sql = query.toString();

        Query q = session.createQuery(sql);

        q.setFirstResult(0);
        q.setMaxResults(2);

        QueryPos qPos = QueryPos.getInstance(q);

        qPos.add(skillId);

        if (orderByComparator != null) {
            Object[] values = orderByComparator.getOrderByValues(skillUser);

            for (Object value : values) {
                qPos.add(value);
            }
        }

        List<SkillUser> list = q.list();

        if (list.size() == 2) {
            return list.get(1);
        } else {
            return null;
        }
    }

    public List<SkillUser> findAll() throws SystemException {
        return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
    }

    public List<SkillUser> findAll(int start, int end)
        throws SystemException {
        return findAll(start, end, null);
    }

    public List<SkillUser> findAll(int start, int end,
        OrderByComparator orderByComparator) throws SystemException {
        Object[] finderArgs = new Object[] {
                String.valueOf(start), String.valueOf(end),
                String.valueOf(orderByComparator)
            };

        List<SkillUser> list = (List<SkillUser>) FinderCacheUtil.getResult(FINDER_PATH_FIND_ALL,
                finderArgs, this);

        if (list == null) {
            Session session = null;

            try {
                session = openSession();

                StringBundler query = null;
                String sql = null;

                if (orderByComparator != null) {
                    query = new StringBundler(2 +
                            (orderByComparator.getOrderByFields().length * 3));

                    query.append(_SQL_SELECT_SKILLUSER);

                    appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
                        orderByComparator);

                    sql = query.toString();
                }

                sql = _SQL_SELECT_SKILLUSER;

                Query q = session.createQuery(sql);

                if (orderByComparator == null) {
                    list = (List<SkillUser>) QueryUtil.list(q, getDialect(),
                            start, end, false);

                    Collections.sort(list);
                } else {
                    list = (List<SkillUser>) QueryUtil.list(q, getDialect(),
                            start, end);
                }
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (list == null) {
                    list = new ArrayList<SkillUser>();
                }

                cacheResult(list);

                FinderCacheUtil.putResult(FINDER_PATH_FIND_ALL, finderArgs, list);

                closeSession(session);
            }
        }

        return list;
    }

    public void removeByUserId(long userId) throws SystemException {
        for (SkillUser skillUser : findByUserId(userId)) {
            remove(skillUser);
        }
    }

    public void removeBySkillId(long skillId) throws SystemException {
        for (SkillUser skillUser : findBySkillId(skillId)) {
            remove(skillUser);
        }
    }

    public void removeAll() throws SystemException {
        for (SkillUser skillUser : findAll()) {
            remove(skillUser);
        }
    }

    public int countByUserId(long userId) throws SystemException {
        Object[] finderArgs = new Object[] { new Long(userId) };

        Long count = (Long) FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_USERID,
                finderArgs, this);

        if (count == null) {
            Session session = null;

            try {
                session = openSession();

                StringBundler query = new StringBundler(2);

                query.append(_SQL_COUNT_SKILLUSER_WHERE);

                query.append(_FINDER_COLUMN_USERID_USERID_2);

                String sql = query.toString();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(userId);

                count = (Long) q.uniqueResult();
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (count == null) {
                    count = Long.valueOf(0);
                }

                FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_USERID,
                    finderArgs, count);

                closeSession(session);
            }
        }

        return count.intValue();
    }

    public int countBySkillId(long skillId) throws SystemException {
        Object[] finderArgs = new Object[] { new Long(skillId) };

        Long count = (Long) FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_SKILLID,
                finderArgs, this);

        if (count == null) {
            Session session = null;

            try {
                session = openSession();

                StringBundler query = new StringBundler(2);

                query.append(_SQL_COUNT_SKILLUSER_WHERE);

                query.append(_FINDER_COLUMN_SKILLID_SKILLID_2);

                String sql = query.toString();

                Query q = session.createQuery(sql);

                QueryPos qPos = QueryPos.getInstance(q);

                qPos.add(skillId);

                count = (Long) q.uniqueResult();
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (count == null) {
                    count = Long.valueOf(0);
                }

                FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_SKILLID,
                    finderArgs, count);

                closeSession(session);
            }
        }

        return count.intValue();
    }

    public int countAll() throws SystemException {
        Object[] finderArgs = new Object[0];

        Long count = (Long) FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
                finderArgs, this);

        if (count == null) {
            Session session = null;

            try {
                session = openSession();

                Query q = session.createQuery(_SQL_COUNT_SKILLUSER);

                count = (Long) q.uniqueResult();
            } catch (Exception e) {
                throw processException(e);
            } finally {
                if (count == null) {
                    count = Long.valueOf(0);
                }

                FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL, finderArgs,
                    count);

                closeSession(session);
            }
        }

        return count.intValue();
    }

    public void afterPropertiesSet() {
        String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
                    com.liferay.util.service.ServiceProps.get(
                        "value.object.listener.org.openwork.portlet.skillmanagement.model.SkillUser")));

        if (listenerClassNames.length > 0) {
            try {
                List<ModelListener<SkillUser>> listenersList = new ArrayList<ModelListener<SkillUser>>();

                for (String listenerClassName : listenerClassNames) {
                    listenersList.add((ModelListener<SkillUser>) InstanceFactory.newInstance(
                            listenerClassName));
                }

                listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
            } catch (Exception e) {
                _log.error(e);
            }
        }
    }
}
